package com.zmj.common.base;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.util.StringUtils;

import java.lang.reflect.Method;

/**
 * mybatis-plus自动填充属性处理器
 *
 * @author zmj
 * @date 2021-12-14 08:47
 */
public class MyMetaObjectHandler implements MetaObjectHandler {


    /**
     * 插入自动填充
     *
     * @param metaObject
     */
    @Override
    public void insertFill(MetaObject metaObject) {
        this.strictInsertFill(metaObject, "optUser", String.class, "自动插入-bill");
    }


    /**
     * 更新自动填充
     *
     * @param metaObject
     */
    @Override
    public void updateFill(MetaObject metaObject) {
        setOptValueNull(metaObject, "optUser", String.class);
        this.strictUpdateFill(metaObject, "optUser", String.class, "自动更新-小明");
    }


    /**
     * @param metaObject 操作对象
     * @param fileName   需置null字段
     */
    private void setOptValueNull(MetaObject metaObject, String fileName, Class clazz) {
        Object originalObject = metaObject.getOriginalObject();
        String setFun = "set" + StringUtils.capitalize(fileName);
        Method method;
        try {
            method = originalObject.getClass().getMethod(setFun, clazz);
            method.invoke(originalObject, new Object[]{null});
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
